<template>
  <div class="halt">
    <div :class="[showExpand?'search-title-more':'search-title']">查询条件</div>
    <div class="search-box">
      <a-form-model :model="searchForm" layout="inline" ref="searchForm" class="searchForm searchMoreForm" :style="{height:expanded? 'auto' : '40px'}">
        <a-row style="width: 100%">
          <a-col :xl="8" :xxl="6">
            <a-form-model-item label="机台号"  prop="machineNo">
              <a-input v-model="searchForm.machineNo" :allowClear=true placeholder="请输入机台号"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :xxl="6">
            <a-form-model-item label="生产订单号"  prop="orderNum">
              <a-input v-model="searchForm.orderNum" :allowClear=true placeholder="请输入生产订单号"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :xxl="6">
            <a-form-model-item label="数据设备类型"  prop="resourceDeviceType">
              <a-select v-model="searchForm.resourceDeviceType" :allowClear=true placeholder="请选择数据设备类型">
                <a-select-option  key="" value="0" >
                  I型
                </a-select-option>
                <a-select-option  key="" value="1" >
                  II型
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :xxl="6">
            <a-form-model-item label="上传时间" prop="makeTimeValue">
              <a-range-picker
                v-model="searchForm.makeTimeValue"
                style="width: 100%"
                @change="onChangeMakeTimeValue"
                :disabledDate="disabledDate"
                @calendarChange="onChange"
                @openChange="openChange"
                valueFormat="YYYY-MM-DD"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div class="searchButton">
        <a-button type="primary" v-if="QX.read" @click="getSearch">查询</a-button>
        <a-button type="default" v-if="QX.read" @click="restSearch('searchForm')">重置</a-button>
      </div>
      <div v-if="showExpand" class="expand" @click="switchHeight">
        <span v-if="expanded==true">收起<a-icon type="up" /></span>
        <span v-else>展开<a-icon type="down" /></span>
      </div>
    </div>
    <div class="table-operation">
      <a-button type="primary" @click="upload" icon="upload" v-if="QX.add&&QX.upload">导入</a-button>
      <a-button type="primary" @click="downLoad" icon="download" v-if="QX.download" :loading="downloading">导出</a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="false"
      :loading="loading"
      rowKey="equipDataId"
      :scroll="{x:1050,y: scrollY }">
      <template
        v-for="col in columns"
        :slot="col.key"
        slot-scope="text,record"
      >
        <span v-if="col.key=='typeName'">
         <span v-if="text==''"></span>
        <span v-else-if="text=='Ⅰ型'"><a-tag color="blue">{{text}}</a-tag></span>
         <span v-else><a-tag color="cyan">{{text}}</a-tag></span>
      </span>
        <span v-else-if="col.key=='action'">
          <a @click="detail(record)" v-if="QX.read"><a-icon class="iconBtn" type="eye"/>详情</a>
        </span>
        <span v-else>
          <TableTootip :content="text"></TableTootip>
        </span>
      </template>
    </a-table>
    <a-pagination
      show-size-changer
      :total="totalPage"
      :current="pageIndex"
      :pageSize="pageSize"
      @showSizeChange="onShowSizeChange"
      @change="onChangePage"
      style="float: right;margin-top: 15px"
    />
    <a-modal centered="true" v-model="visible" :title="title">
      <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="form" class="lay-drawer-form">
        <a-form-model-item label="上传文件" prop="file" v-if="showUpload" :help="helpUpload">
          <div class="clearfix">
            <a-upload :fileList="fileList" :remove="handleRemove" :beforeUpload="beforeUpload" accept=".xls,.xlsx">
              <a-button>
                <a-icon type="upload"/>
                文件上传
              </a-button>
            </a-upload>
          </div>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-popconfirm :visible="visibleSub" placement="topRight" ok-text="是" cancel-text="否" @cancel="cancelVisibleSub"
                      @confirm="updateFileStatus">
          <template slot="title">
            <p>文件名称重复,是否覆盖原文件！</p>
            <p>若不覆盖，请修改文件名称后重新上传！</p>
          </template>
          <a-button type="info" @click="visible = false;">取消</a-button>
          <a-button
            type="primary"
            @click="handleUpload"
            :disabled="fileList.length === 0"
            :loading="uploading"
            style="margin-left: 8px"
          >
            {{ uploading ? '上传中' : '确认' }}
          </a-button>
        </a-popconfirm>
      </template>
    </a-modal>

    <a-modal width="1150" height="420"  centered="true" :footer="null" v-model="visibleDetail" :title="title">
      <a-table
        :columns="columnsDetail"
        :data-source="detailList"
        :pagination="false"
        :loading="loadingDetail"
        rowKey="sequ_code"
        style="width: 1130px"
        :scroll="{x: 1120,y: this.$getViewportSize().height-280 }">
        <template
          v-for="col in columnsDetail"
          :slot="col.key"
          slot-scope="text,record"
        >
          <span>
          <TableTootip :content="text"></TableTootip>
        </span>
        </template>
      </a-table>
      <div class="modalPage">
        <a-pagination
          show-size-changer
          :total="totalPageDetail"
          :current="pageIndexDetail"
          :pageSize="pageSizeDetail"
          @change="onChangePageDetail"
          @showSizeChange="onShowSizeChangeDetail"
          style="float: right;margin-top: 15px"
        />
      </div>
    </a-modal>
  </div>
</template>
<script>
import preventBack from 'vue-prevent-browser-back';
import {fileDownload, req} from "../../api/axiosFun";
import axios from "axios";
import moment from "moment";
import {getScrollY} from "../../until";
import TableTootip from '../../components/TableTootip.vue'
export default {
  name: "DeviceData",
  mixins: [preventBack],//注入
  components:{
    TableTootip
  },
  data(){
    return {
      QX: {},
      labelCol: {span: 4},
      wrapperCol: {span: 20},
      searchForm: {
        machineNo:'',
        resourceDeviceType:undefined,
        startTime:'',
        endTime: '',
        orderNum: '',
        makeTimeValue: []
      },
      expanded: false,//筛选条件是否展开
      dataList: [],
      columns,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      pageIndexDetail: 1,
      pageSizeDetail: 10,
      totalPageDetail: 0,
      visible: false,
      visibleSub: false,
      visibleDetail: false,
      showUpload: true,
      downloading: false,
      uploading: false,
      loading: false,
      loadingDetail: false,
      helpUpload:'上传资源大小不能超过10MB',
      fileList: [],
      equipDataId:'',
      form: {
        file: ''
      },
      rules: {},
      detailList:[],
      columnsDetail,
      showExpand: false,
      scrollY: 0
    }
  },
  watch: {
    visible(val) {
      if(!val){
        this.fileList = []
      }
    },
    visibleDetail(val) {
      if(!val){
        this.pageIndexDetail = 1
      }
    }
  },
  mounted() {
    this.showExpand = document.body.clientWidth <= 1440
    window.onresize = () => {
      //屏幕尺寸变化
      return (() => {
        this.showExpand = document.body.clientWidth <= 1440
      })()
    }
    this.getDataList()
    setTimeout(()=>{
      this.scrollY = getScrollY(this.$refs.searchForm.$el.offsetHeight,280)
    },0)
  },
  methods: {
    moment,
    switchHeight(){//切换查询条件高度
      this.expanded=!this.expanded
      setTimeout(()=>{
        this.scrollY = getScrollY(this.$refs.searchForm.$el.offsetHeight,280)
      },0)
    },
    /* 日期面板打开关闭事件 */
    openChange(status) {
      this.disabledCurrent = null
    },
    /* 选中日期改变事件 */
    onChange(dates) {
      this.disabledCurrent = dates[0]
    },
    /* 日期禁用回调 */
    disabledDate(current) {
      if (!this.disabledCurrent) return current > moment()
      return (current && current <= moment(this.disabledCurrent).subtract(1, 'M')) || current >= moment(this.disabledCurrent).add(1, 'M') || current > moment()
    },
    onChangeMakeTimeValue(date) {
      if(date.length) {
        this.searchForm.startTime = date[0]
        this.searchForm.endTime = date[1]
      }else {
        this.searchForm.startTime = ''
        this.searchForm.endTime = ''
      }
    },
    //查询
    getSearch() {
      this.pageIndex = 1
      this.getDataList()
    },
    /* 重置查询 */
    restSearch(form) {
      this.restForm(form);
      this.searchForm.startTime = ''
      this.searchForm.endTime = ''
      this.pageIndex = 1
      this.getDataList();
    },
    /* 重置表单 */
    restForm(form) {
      this.$refs[form].resetFields();
    },
    /* 改变页数事件 */
    onChangePage(page, pageSize) {
      this.pageIndex = page;
      this.getDataList();
    },
    /* 改变每页显示条数 */
    onShowSizeChange(current, pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.getDataList();
    },
    /* 改变页数事件 */
    onChangePageDetail(page, pageSize) {
      this.pageIndexDetail = page;
      this.getDataRecord();
    },
    /* 改变每页显示条数 */
    onShowSizeChangeDetail(current, pageSize) {
      this.pageIndexDetail = 1;
      this.pageSizeDetail = pageSize;
      this.getDataRecord();
    },
    /* 列表 */
    getDataList() {
      this.loading = true;
      this.searchForm.page = this.pageIndex;
      this.searchForm.rows = this.pageSize;
      var searchForm = {}
      for (var key in this.searchForm) {
        searchForm[key] = this.searchForm[key]||''
      }
      req("post", `deviceData/getDataList`, searchForm)
        .then(res => {
          if (res.result === 'success') {
            this.dataList = res.data;
            this.totalPage = res.page.totalResult;
            this.QX = res.QX;
          }
          this.loading = false;
        }).catch(e => {
        this.loading = false;
      });
    },
    downLoad() {
      var searchForm = {
        machineNo:this.searchForm.machineNo||'',
        resourceDeviceType:this.searchForm.resourceDeviceType||'',
        startTime:this.searchForm.startTime?(this.searchForm.startTime+' 00:00:00'):'',
        endTime: this.searchForm.endTime?(this.searchForm.endTime+' 00:00:00'):'',
        orderNum: this.searchForm.orderNum||'',
      }
      if(this.searchForm.machineNo==''&&this.searchForm.orderNum==''&&searchForm.resourceDeviceType==''&&this.searchForm.makeTimeValue.length==0){
        this.$message.warning('请选择筛选条件进行设备数据的导出')
        return
      }
      this.downloading = true
      fileDownload('post', 'deviceData/exportDeviceData',searchForm)
        .then(res => {
          this.downloading = false
          this.$message.destroy();
          if (res.type === 'application/vnd.ms-excel') {
            let blob = new Blob([res]);
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, '设备数据.xlsx');
            } else {
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(blob);
              link.download = '设备数据.xlsx';
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
              this.exporting = false;
              this.loading = false;

            }
          } else if (res.type === 'application/json') {
            const reader = new FileReader();
            reader.addEventListener('loadend', function (e) {
              let text = e.target.result;
              let parse = JSON.parse(text);
              if (parse.result !== 'success') {
                // that.$message.error(parse.message);
              }
            });
            reader.readAsText(res);
            this.exporting = false;
            this.loading = false;
          }
        }, error => {
          if (error.toString()
            .indexOf('timeout') > 0) {
            this.$message.warning('请求导出超时,数据量过大。');
            this.exporting = false;
            this.loading = false;

          }
        });
    },
    upload() {
      this.title='导入'
      this.visible = true
    },
    //点击删除文件
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    //点击上传文件
    beforeUpload(file) {
      let isSize = file.size/1024/1024 <=10
      if (!isSize){
        this.$message.warning('资源大小超出限制，请修改后重新上传！')
        return false
      }
      this.fileList.length = 0;
      this.fileList = [...this.fileList, file];
      return false;
    },
    //修改确认框状态
    updateFileStatus() {
      this.form.fileStatus = '1';
      this.handleUpload();
      this.visibleSub = false;
    },
    //关闭确认框
    cancelVisibleSub() {
      this.visibleSub = false;
    },
    //新增和修改方法
    handleUpload() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const { fileList } = this;
          const formData = new FormData();
          fileList.forEach(file => {
            formData.append('file', file);
          });
          this.uploading = true;
          axios(
            {
              method: 'post',
              url: 'deviceData/insertDeviceData',
              headers: {
                'Access-Token': localStorage.getItem('token')
              },
              data: formData
            })
            .then((response) => {
              this.uploading = false;
              if (response.data.result === 'success') {
                this.fileList = [];
                this.visible = false;
                this.getDataList();
                this.form.fileStatus = '0';
                this.$message.success('导入成功');
              } else {
                if (response.data.fileStatus == 1) {
                  this.visibleSub = true;
                } else if (response.data.result === 'failed') {
                  this.$message.warning(response.data.message);
                } else {
                  this.$message.error(response.data.message);
                }
              }
            })
            .catch(error => {
              if (error.response.status === 403) {
                //没权限
                this.$message.warning(error.response.data.message);
              } else {
                this.$message.error(error.response.data.message);
              }
              this.uploading = false;
            });
        }
      });
    },
    detail(record) {
      this.title = '详情'
      this.equipDataId = record.equipDataId
      this.loading = true
      this.getDataRecord(record);
    },
    //详情
    getDataRecord(record){
      this.loadingDetail = true;
      req("post", 'deviceData/dataRecord', {
        equipDataId:this.equipDataId,
        page:this.pageIndexDetail,
        rows:this.pageSizeDetail

      }).then(res => {
        this.loadingDetail = false;
        this.loading = false
        if (res.result === 'success') {
          if(this.visibleDetail == false){
            this.visibleDetail = true
          }
          this.detailList = res.data
          this.totalPageDetail = res.page.totalResult;
        }
      }).catch(e => {
        this.loadingDetail = false;
      });
    }
  }
}
const columns = [
  {
    title: '序号',
    width:'40px',
    align: 'center',
    customRender: (text, row, index) => {
      return index+1;
    },
  },
  {
    title: '机台号',
    align: 'center',
    dataIndex: 'machineNo',
    key: 'machineNo',
    width: 90,
    scopedSlots: {customRender: 'machineNo'},
  },
  {
    title: '生产订单号',
    align: 'center',
    dataIndex: 'orderNum',
    key: 'orderNum',
    width: 110,
    scopedSlots: {customRender: 'orderNum'},
  },
  {
    title: '总数',
    align: 'center',
    dataIndex: 'total',
    key: 'total',
    scopedSlots: {customRender: 'total'},
    width: 70
  },
  {
    title: '不合格数',
    align: 'center',
    dataIndex: 'ngQuntity',
    key: 'ngQuntity',
    scopedSlots: {customRender: 'ngQuntity'},
    width: 70
  },
  {
    title: '合格数',
    align: 'center',
    dataIndex: 'okPlateQuntity',
    key: 'okPlateQuntity',
    scopedSlots: {customRender: 'okPlateQuntity'},
    width: 70
  },
  {
    title: '数据设备类型',
    dataIndex: 'typeName',
    align:'center',
    key: 'typeName',
    scopedSlots: {customRender: 'typeName'},
    width: 90,
  },
  {
    title: '测试时间',
    dataIndex: 'testTime',
    align:'center',
    key: 'testTime',
    scopedSlots: {customRender: 'testTime'},
    width: 140
  },
  {
    title: '上传时间',
    dataIndex: 'uploadDatetime',
    align:'center',
    key: 'uploadDatetime',
    scopedSlots: {customRender: 'uploadDatetime'},
    width: 290
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    align: 'center',
    width: 80,
    scopedSlots: {customRender: 'action'},
  }
];
const columnsDetail = [
  {
    title: '序号',
    align: 'center',
    width: '40px',
    customRender: (text, record, index) => `${index + 1}`,
  },
  // {
  //   title: '通道',
  //   align: 'center',
  //   dataIndex: 'channel',
  //   key: 'channel',
  //   width: '50px',
  //   fixed: 'left',
  // },
  {
    title: '状态码',
    align: 'center',
    dataIndex: 'status_code',
    key: 'status_code',
    scopedSlots: {customRender: 'status_code'},
    width: 50
  },
  {
    title: '内码',
    align: 'center',
    dataIndex: 'sequ_code',
    key: 'sequ_code',
    width: 150,
    scopedSlots: {customRender: 'sequ_code'},
  },
  {
    title: '频率',
    align: 'center',
    dataIndex: 'frequency',
    key: 'frequency',
    scopedSlots: {customRender: 'frequency'},
  },
  {
    title: '芯片类型',
    align: 'center',
    dataIndex: 'type',
    key: 'type',
    scopedSlots: {customRender: 'type'},
    width: 65
  },
  {
    title: '正向电流(LV)',
    align: 'center',
    dataIndex: 'forward_lv',
    key: 'forward_lv',
    scopedSlots: {customRender: 'forward_lv'},
  },
  {
    title: '反向电流(LV)',
    align: 'center',
    dataIndex: 'reverse_lv',
    key: 'reverse_lv',
    scopedSlots: {customRender: 'reverse_lv'},
  },
  {
    title: '正向电流(HV)',
    align: 'center',
    dataIndex: 'forward_hv',
    key: 'forward_hv',
    scopedSlots: {customRender: 'forward_hv'},
  },
  {
    title: '反向电流(HV)',
    align: 'center',
    dataIndex: 'reverse_hv',
    key: 'reverse_hv',
    scopedSlots: {customRender: 'reverse_hv'},
  },
  {
    title: '起爆电容漏电',
    align: 'center',
    dataIndex: 'cap_leakage',
    key: 'cap_leakage',
    scopedSlots: {customRender: 'cap_leakage'},
  },
  {
    title: '桥头',
    align: 'center',
    dataIndex: 'bridge',
    key: 'bridge',
    scopedSlots: {customRender: 'bridge'},
    width: 40
  },
  {
    title: '电容',
    align: 'center',
    dataIndex: 'cap',
    key: 'cap',
    scopedSlots: {customRender: 'cap'},
    width: 40
  },
  {
    title: '上传时间',
    align: 'center',
    dataIndex: 'upload_time',
    key: 'upload_time',
    scopedSlots: {customRender: 'upload_time'},
    width: 140
  },
];
</script>
<style scoped>
@import "../../assets/css/maincss.css";

</style>
